//begin of index.js
var pages = pages || {};

(function(pages) {
  pages.index = {
    listOpr: {
      requestLimit: 0,
      tryGetList: function() {
        this.requestLimit += 1;
        if (this.requestLimit > 3) {
          $("#items").html("<h1>Unable To Load</h1>");
          return;
        }
        $.ajax({
          url: 'api.asp',
          type: 'POST',
          data: {
            'action': 'getList'
          },
          dataType: 'text',
          timeout: 1000,
          async: false,
          error: function() {
            //获取失败，就继续获取
            setTimeout(this.tryGetList, 100);
          },
          success: function(result) {
            $('#items').html(result);
          }
        });
      }
    },
    inputBoxMng: {
      init: function() {
        $('#FunctionName').val('');
        $('#Language').val('');
        $('#FuncType').val('');
        $('#FunctionCode').val('');
        $('#Creator').val('');
      },
      show: function() {
        var nClientWidth = document.body.clientWidth;
        var nClientHeight = document.body.clientHeight;
        var nBoxWidth = $('#float_post').width();
        var nBoxHeight = $('#float_post').height();
        var nTargetLeft = (nClientWidth - nBoxWidth) / 2;
        var nTargetTop = (nClientHeight - nBoxHeight) / 2 - 50;
        $('#float_post').css({
          'left': nTargetLeft,
          'top': nTargetTop,
          'display': 'block'
        });
        $('#FunctionName').focus();
      },
      hide: function() {
        $('#float_post').css({
          'display': 'none'
        });
      },
      display: function() {
        this.init();
        this.show();
      }
    },
    localData: {
      showTime: 5
    },
    init: function() {
      _pageBindings();
      this.expose();
    },
    expose: function() {
      //将本页面需要的函数暴露出来
      window.viewCode = _viewCode;
    },
    coverControl: {
      setOn: function() {
        var cover = $('#this_cover');
        if (cover.hasClass('cover_off')) {
          $('#this_cover').removeClass('cover_off');
        }
        if (!cover.hasClass('cover_on')) {
          $('#this_cover').addClass('cover_on');
        }
      },
      setOff: function() {
        var cover = $('#this_cover');
        if (!cover.hasClass('cover_off')) {
          $('#this_cover').addClass('cover_off');
        }
        if (cover.hasClass('cover_on')) {
          $('#this_cover').removeClass('cover_on');
        }
      },
      setMsg: function(width, height, msg) {
        //get left of content
        var oContentPos = $('#info_content_uu').offset();
        var nLeft = oContentPos.left;
        var nTop = oContentPos.top;
        var nBoxWidth = $('#info_content_uu').width();
        var nBoxHeight = $('#info_content_uu').height();
        var nTargetLeft = nLeft + (nBoxWidth - width) / 2;
        var nTargetTop = nTop + (nBoxHeight - height) / 2 - 50;
        $('#this_cover').css({
          'left': nTargetLeft,
          'top': nTargetTop,
          'width': width,
          'height': height
        });
        $('#this_cover').css({
          'line-height': height + 'px'
        });
        $('#this_cover').html(msg);
      }
    },
    panelMng: {
      post: function() {
        if (!this.valid()) return; //如果输入框检查不通过则退出。
        pages.index.coverControl.setOn();
        pages.index.coverControl.setMsg(200, 50, '正在提交...');
        var sFuncName = $('#FunctionName').val();
        var sCodeLanguage = $('#Language').val();
        var sCodeType = $('#FuncType').val();
        var sCode = $('#FunctionCode').val();
        var sCreator = $('#Creator').val();
        $.ajax({
          url: 'api.asp',
          type: 'post',
          data: {
            'action': 'submit_newcode',
            'funcName': sFuncName,
            'funcLan': sCodeLanguage,
            'funcType': sCodeType,
            'funcCode': sCode,
            'CreatorMail': sCreator
          },
          success: function(data) {
            var oRet = pages.common.parseJSON(data);
            if (oRet) {
              if (oRet.ref == 'ok') {
                pages.index.listOpr.requestLimit = 0;
                pages.index.listOpr.tryGetList();
              }
            }
            pages.index.coverControl.setOff();
            $('#float_post').css({
              'display': 'none'
            });
          }
        });
      },
      valid: function() {
        var sFuncName = $('#FunctionName').val();
        var sCode = $('#FunctionCode').val();
        if (!sFuncName) {
          alert('函数必须要有函数名哦！');
          $('#FunctionName').focus();
          return false;
        }
        if (!sCode) {
          alert('既然提交代码，亲，填上代码吧，咱们程序员提交null是几个意思？');
          $('#FunctionCode').focus();
          return false;
        }
        return true;
      }
    }
  };
  //local functions
  function _pageBindings() {
    //绑定
    $(document).ready(function() {
      //增加代码输入区域的tab支持
      $('#FunctionCode').keydown(function(e) {
        if (e.keyCode == 9) {
          e.preventDefault();
          var start = this.selectionStart,
            end = this.selectionEnd;
          var text = this.value;
          var tab = '    ';
          text = text.substr(0, start) + tab + text.substr(start);
          this.value = text;
          this.selectionStart = start + tab.length;
          this.selectionEnd = end + tab.length;
        }
      });
      //绑定提交按钮的处理函数
      $('#submit_form').click(function() {
        pages.index.panelMng.post();
      });

      //输入框相关
      ////”发布代码“按钮
      $('.btn_NewPost').on('click', function() {
        pages.index.inputBoxMng.display()
      });
      //'关闭'按钮
      $('#close_form').on('click', function() {
        pages.index.inputBoxMng.hide();
      });


      //Ajax请求列表
      pages.index.listOpr.tryGetList();
      $('#txtSearch').keyup(function() {
        var sTitle = $('#txtSearch').val();
        var sUrlCode;
        if (sTitle.length == 0) {
          sUrlCode = PageLib.AjaxGetText('api.asp', {
            'action': 'getList'
          });
        } else {
          sUrlCode = PageLib.AjaxGetText('api.asp', {
            'action': 'searchToList',
            'keyword': sTitle
          });
        }

        $('#items').html(sUrlCode);
      });

      //复制代码-按钮
      $('#btncopy').click(function() {
        var sCode = $('#hidcode').val();
        if (sCode.length == 0) {
          return;
        };
        //判断显示区域是否存在
        var oDisplayZone = $('#info_content');
        if (oDisplayZone.length == 0) {
          return;
        };
        //记录原显示区域位置
        var nLeft = oDisplayZone.offset().left;
        var nTop = oDisplayZone.offset().top;

        //var nHeight = oDisplayZone.height();
        var nHeight = document.body.clientHeight - 250;
        var nWidth = oDisplayZone.width();
        $('#info_content_uu').html('<textarea id="text_copy"></textarea>');
        $('#text_copy').html(sCode);
        $('#text_copy').css({
          'left': nLeft,
          'top': nTop
        });
        $('#text_copy').css({
          'height': nHeight,
          'width': nWidth,
          'margin-top': '13px'
        });
        $('#text_copy').select();
      });
      _redisplay();
    });
  }

  //function to navigate from this page to new page
  function _redisplay() {
    if (pages.index.localData.showTime == 5) {
      //调整显示
      var nBoxHeight = 200;
      var nBoxWidth = 400;
      var nWidth = document.body.clientWidth;
      var nHeight = document.body.clientHeight;
      var nLeft = (nWidth - nBoxWidth) / 2;
      var nTop = (nHeight - nBoxHeight) / 2;
      var o = $('#trynews');
      o.show();
      o.css('left', nLeft);
      o.css('top', nTop);
      o.css('z-index', 9999);
      o.css('width', nBoxWidth);
      o.css('height', nBoxHeight);
      o.css('position', 'absolute');
      o.css('background-color', 'rgb(170,181,195)');
      o.css('line-height', nBoxHeight + 'px');
      o.css('font-size', '40px');
      o.css('border-radius', '10px');
      o.css('text-align', 'center');
    }
    if (pages.index.localData.showTime > 0) {
      pages.index.localData.showTime--;
      $('#trynews_link').text('体验新版(' + pages.index.localData.showTime + ')');
      setTimeout(_redisplay, 1000);
    }
    if (pages.index.localData.showTime <= 0) {
      //pages.common.control.goTo('index_new.asp');
      $("#trynews").fadeOut(500);
    }
  }

  //显示选中的代码
  function _viewCode(sId) {
    pages.index.coverControl.setOn();
    pages.index.coverControl.setMsg(200, 50, '正在加载...');
    $.ajax({
      url: 'api.asp',
      type: 'post',
      data: {
        'action': 'view',
        'id': sId
      },
      success: function(data) {
        var oRet = pages.common.parseJSON(data);
        if (oRet) {
          if (oRet.ref == 'ok') {
            $('#title').html(oRet.name);
            $('#title').attr('title', $('<div/>').html(oRet.name).text());

            //$("#info_content").html(oRet.code.replace(/\n/g, "<br />"));
            //先创建标签
            //<pre id=""info_content""></pre>
            $('#info_content_uu').html('<pre id="info_content"></pre>');
            $("#info_content").html(oRet.code);
            $("#hidcode").val(oRet.code);
            $("#dis_Language").html(oRet.Language);
            $("#dis_Type").html(oRet.Type);
            $("#dis_Creator").html(oRet.CreatorMail);
            var sCodeType = oRet.Language.toLowerCase()
            switch (sCodeType) {
              case 'vb.net':
              case 'vbs':
              case 'vb':
                $("#info_content").attr("class", "brush: vb;");
                break;
              case 'c':
              case 'c++':
              case 'cpp':
                $("#info_content").attr("class", "brush: c;");
                break;
              case 'javascript':
                $("#info_content").attr("class", "brush: js;");
                break;
            }
            //SyntaxHighlighter.all();
            // var br = SyntaxHighlighter.vars.discoveredBrushes;
            // br['js']='Js';
            SyntaxHighlighter.vars.discoveredBrushes = null;
            SyntaxHighlighter.autoloader(
              'js jscript javascript  /js/codebeautify/shBrushJScript.js',
              'vb vbnet              /js/codebeautify/shBrushVb.js',
              'ruby                   /js/codebeautify/shBrushRuby.js',
              'c     /js/codebeautify/shBrushCpp.js'
            );
            SyntaxHighlighter.all()
            var nHeight = $('#info_content').height();
            $("div[id^='highlighter']").attr("style", "overflow:hidden !important;height:100%");
            $("#info_content").css({
              "height": nHeight
            });
          }
        }
        pages.index.coverControl.setOff();
      }
    });
  }
})(pages);

var PageLib = {
  AjaxGetText: function(url, option) {
    var sResult;
    $.ajax({
      url: url,
      type: 'POST',
      data: option,
      dataType: 'text',
      timeout: 1000,
      async: false,
      error: function() {
        sResult = "";
      },
      success: function(result) {
        sResult = result;
      }
    });
    return sResult;
  }
};

//end of index.js